package cn.lynch.bbs.util.converter;

import org.apache.commons.beanutils.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EnumBeanUtilConverter implements Converter {
	private static final Logger logger = LoggerFactory.getLogger(EnumBeanUtilConverter.class);

	private Object defaultValue;
	
	private boolean useDefault = true;
	
	@SuppressWarnings("unchecked")
	private Class<? extends Enum> enumClass;
	
	public EnumBeanUtilConverter() {
	}
	
	public EnumBeanUtilConverter(boolean useDefault) {
		super();
		this.useDefault = useDefault;
	}

	public EnumBeanUtilConverter(Object defaultValue,
			boolean useDefault) {
		super();
		this.defaultValue = defaultValue;
		this.useDefault = useDefault;
	}


	@SuppressWarnings("unchecked")
	@Override
	public Object convert(Class clz, Object value) {
		
		if (clz.isInstance(value)) {
			return value;
		}
		
		if (value == null) {
			return useDefault ? defaultValue : null;
		}
		
		try {
			return Enum.valueOf(enumClass, (String)value);
		}catch (Exception e) {
			logger.error("convert(Class, Object)", e);

			return useDefault ? defaultValue : null;
		}
	}

}
